package fr.poy.mygluco.client;

import com.extjs.gxt.ui.client.GXT;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.RootPanel;

import fr.poy.mygluco.client.gxt.BaseAsyncCallback;
import fr.poy.mygluco.client.ui.Main;
import fr.poy.mygluco.client.ui.MessageHandler;
import fr.poy.mygluco.model.AppLogs;
import fr.poy.mygluco.model.UserProfile;

/**
 * entry point.
 */
public class App implements EntryPoint {
	
	private final static AppServiceAsync service = GWT.create(AppService.class);
	private final static AppConstants constants = GWT.create(AppConstants.class);
	private final static AppMessages messages = GWT.create(AppMessages.class); 
	
	private static UserProfile userProfile ;

	//Registry.register("serviceLocal", new ServiceLocal()) ;
	
	public void onModuleLoad() {
		service.loadProfile(new BaseAsyncCallback<UserProfile>(){
			public void onSuccess(final UserProfile s) { 
				App.setUserProfile(s); 
				RootPanel.get().add(new Main());  
				MessageHandler.get().show(App.getMessages().statusWelcome(""+s.getUserEmail() )); 
				GXT.hideLoadingPanel("loading");   
			}   
		});  
	}
	
	public static void saveProfile(){
		service.saveProfile(userProfile, new BaseAsyncCallback<AppLogs>() );
	}

	public static AppServiceAsync getService(){
		return service;
	}

	public static AppConstants getConstants() {
		return constants;
	}

	public static AppMessages getMessages() {
		return messages;
	}

	public static UserProfile getUserProfile() {
		return userProfile;
	}

	private static void setUserProfile(UserProfile userProfile) {
		App.userProfile = userProfile; 
		if(App.userProfile.isFirstuse()){//firstuse; save defaut values;
			App.userProfile.setTimeZone(constants.timeZone());  
			App.userProfile.setDayFormat(constants.dayFormat()); 
			App.userProfile.setDateFormat(constants.dateFormat()); 
			App.userProfile.setTimeFormat(constants.timeFormat()); 
			App.userProfile.setBgUnit(constants.bgUnit()); 
			App.userProfile.setBgHigh(constants.bgHigh()); 
			App.userProfile.setBgLow(constants.bgLow()); 
			App.userProfile.setLimitHypo(constants.limitHypo());  
			App.userProfile.setXmppPattern(constants.xmppPattern());  
			//marche pas pour update post prod
			saveProfile();
		}
		
	}

 
	
	
	
}
